package artid.com.arttogoa;

import org.apache.commons.lang3.StringUtils;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import artid.com.arttogoa.R;

import artid.com.arttogoa.app.ArtWorkApp;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.db.DataKeeper;
import artid.com.arttogoa.parser.UserItem;
import artid.com.arttogoa.util.AlertUtils;
import artid.com.arttogoa.util.AppUtil;
import artid.com.arttogoa.util.MySharedPreferences;
import artid.com.arttogoa.util.NetUtils;
import artid.com.arttogoa.util.RegexUtil;
import artid.com.arttogoa.util.ToastUtil;
import artid.com.arttogoa.view.MyEditText;
import artid.com.arttogoa.volley.VolleyBasic;
import artid.com.arttogoa.volley.VolleyCallback;
import artid.com.arttogoa.volley.VolleyData;
import artid.com.arttogoa.volley.VolleyMap;
import com.android.volley.VolleyError;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.socialize.utils.Log;

/**
 * 
 * 
 * 项目名称：ArtworkArtA 类名称：LoginAvtivity 类描述：登录页面 创建人：耿卫斌 创建时间：2016年5月16日 下午2:24:07
 * 
 */
public class LoginAvtivity extends BaseActivity implements OnClickListener {
	private Intent in;
	private TextView mLogin, mRegister, mForgetPass;
	private MyEditText phone, passWord;
	private CheckBox eyeBtn;
	private Boolean isRemoteLogin = false;// 是否为异地登陆（默认false）

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		// 注册当前广播
		IntentFilter filter = new IntentFilter("com.LoginAvtivity.receiver");
		registerReceiver(broadcastReceiver, filter);
		isRemoteLogin = getIntent().getBooleanExtra("isRemoteLogin", false);
		WifiManager wifiMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		int wifiState = wifiMgr.getWifiState();
		WifiInfo info = wifiMgr.getConnectionInfo();
		String wifiId = info != null ? info.getSSID() : null;
		System.out.println("wifiId=" + wifiId);
		ArtWorkApp.getInstance().addActivity(this);
		// UpdateConfig.setDebug(true);
		// UmengUpdateAgent.setUpdateOnlyWifi(false);
		// UmengUpdateAgent.update(this);
		initview();
		registerUmPush();
	}

	private void initview() {
		mContext = this;
		mRegister = (TextView) findViewById(R.id.Login_text_to_register);
		mForgetPass = (TextView) findViewById(R.id.Login_text_forget_pass);
		mLogin = (TextView) findViewById(R.id.login_btn);
		mLogin.setOnClickListener(this);
		mRegister.setOnClickListener(this);
		mForgetPass.setOnClickListener(this);
		phone = (MyEditText) findViewById(R.id.login_et_phone);
		passWord = (MyEditText) findViewById(R.id.login_et_pass);
		phone.addTextChangedListener(mTextChangedListener);
		passWord.addTextChangedListener(mTextChangedListener);
		isExistUser();
		eyeBtn = (CheckBox) findViewById(R.id.login_eye_btn);
		eyeBtn.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (isChecked) {
					// 如果选中，显示密码
					passWord.setTransformationMethod(HideReturnsTransformationMethod
							.getInstance());
				} else {
					// 否则隐藏密码
					passWord.setTransformationMethod(PasswordTransformationMethod
							.getInstance());
				}

			}
		});
		conditionJudge();
	}

	/**
	 * 对EditText监听
	 */
	TextWatcher mTextChangedListener = new TextWatcher() {
		private CharSequence temp;

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub
			temp = s;
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
			// mTextView.setText(s);//将输入的内容实时显示
		}

		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			conditionJudge();
		}
	};

	/**
	 * 条件判断
	 */
	private void conditionJudge() {
		// 对按钮的判断是否可用
		if (!StringUtils.isEmpty(phone.getText().toString())
				&& !StringUtils.isEmpty(passWord.getText().toString())
				&& RegexUtil.isMobile(phone.getText().toString())) {
			mLogin.setEnabled(true);
			mLogin.setBackgroundResource(R.drawable.red_frame);
		} else {
			mLogin.setEnabled(false);
			mLogin.setBackgroundResource(R.drawable.zjm_bg_dl);
		}
	}

	/**
	 * 判断是否保存用户登录账号与密码
	 */
	private void isExistUser() {
		String phone_s = MySharedPreferences.getMySharedPreferences(mContext)
				.getValue("Phone", "");
		String password_s = MySharedPreferences
				.getMySharedPreferences(mContext).getValue("PassWord", "");
		phone.setText(phone_s);
		passWord.setText(password_s);
	}
	
	private void registerUmPush(){
		//当推送token获取不到的时候重新注册一下
		if(StringUtils.isEmpty(PushAgent.getInstance(this).getRegistrationId())){
			// 友盟注册
			//注册推送服务，每次调用register方法都会回调该接口
			PushAgent.getInstance(this).register(new IUmengRegisterCallback() {

				@Override
				public void onSuccess(String deviceToken) {
					//注册成功会返回device token
					Log.d("log", "友盟ID：" + deviceToken);
				}

				@Override
				public void onFailure(String s, String s1) {
					Log.d("log", "初始化友盟错误：" + s.toString() + "===" + s1.toString());
				}
			});
		}
	}

	private void login() {
		VolleyBasic.getInstance(LoginAvtivity.this).post(
				Cache.login,
				VolleyMap.getInstance().Login(phone.getText().toString(),
						passWord.getText().toString(), PushAgent.getInstance(this).getRegistrationId()),
						UserItem.class, new VolleyCallback() {
					public void onSuccess(VolleyData vd) {
						// TODO Auto-generated method stub
						System.out.println(vd.getJson());
						UserItem us = (UserItem) vd.getData();
						System.out.println(us.toString());
						DataKeeper.keepSerializable(LoginAvtivity.this, us);
						AppUtil.setUser();
						MySharedPreferences.getMySharedPreferences(mContext)
						.setValue("Phone", phone.getText().toString());
						MySharedPreferences.getMySharedPreferences(mContext)
						.setValue("PassWord",
								passWord.getText().toString());
						if (isRemoteLogin == false) {
							// 判断用户是否上传了头像
							if (!StringUtils.isEmpty(us.getAvatarurl())) {
								in = new Intent(LoginAvtivity.this,
										MainActivity.class);
								startActivity(in);
							} else {
								in = new Intent(LoginAvtivity.this,
										UploadPhotoActivity.class);
								startActivity(in);
								return;
							}
						} else {
							// 发送给VolleyBasic告诉异地登陆成功
							Intent intent2 = new Intent(
									"com.VolleyBasic.receiver");
							intent2.putExtra("isRemoteLogin", true);
							sendBroadcast(intent2);
						}
						finish();
					}

					public void onError(VolleyError volleyError) {

					}
				});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.login_btn:
			if (!NetUtils.isNetworkConnected(mContext)) {
				AlertUtils.initSubmitSumAlertDialog(LoginAvtivity.this,"当前网络不可用");
				return;
			}  
			if (StringUtils.isEmpty(PushAgent.getInstance(this).getRegistrationId())) {
				showToast("请检查您的网络链接是否通畅，请重新登录");
				return;
			}
			login();
			break;
		case R.id.Login_text_to_register:
			// 注册
			in = new Intent(LoginAvtivity.this, RegisterActivity.class);
			startActivity(in);
			break;
		case R.id.Login_text_forget_pass:
			// 忘记密码
			in = new Intent(LoginAvtivity.this, ForgetPasswordActivity.class);
			startActivity(in);
			break;

		default:
			break;
		}
	}

	// 再按一次退出程序
	long backPressTime;

	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN
				&& event.getRepeatCount() == 0) {
			long current = System.currentTimeMillis();
			if (current - backPressTime > 2000) {
				backPressTime = current;
				ToastUtil.commonToast(mContext, "再次按返回键退出程序");
			} else {
				finish();
			}
			return false;
		}
		return super.dispatchKeyEvent(event);
	}

	// 广播监听
	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getBooleanExtra("isRemoteLogin", false)) {
				// 判断是否为异地登陆
				Log.d("log", "LoginActivity接收：异地登陆");
			}
		}
	};

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (TextUtils.isEmpty(passWord.getText().toString().trim())) {
			MySharedPreferences.getMySharedPreferences(mContext).setValue(
					"PassWord", "");
		}
		// 关闭广播
		unregisterReceiver(broadcastReceiver);
	}
}
